package com.hu.config.interceptor;

import com.alibaba.fastjson.JSON;
import com.hu.config.comment.ResponseResult;
import com.hu.config.permission.Roles;
import com.hu.config.redis.TokenCache;
import com.hu.uitl.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.logging.Logger;

@EnableWebMvc
@Configuration
public class MyInter implements HandlerInterceptor {
    Logger logger = Logger.getLogger(MyInter.class.getName());//创建日志，一般以当前类的全类名作为名称

    @Autowired
    private TokenCache TokenCache;

    /**
     * 请求结束，主要用于清理工作。
     */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    /**
     * 请求之后，在视图渲染之前，也就是Controller方法调用之后
     */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
    }


    /**
     * 通过拦截器认证和权限管理----请求之前，也就是Controller方法调用之前。
     * 1.可以重定向到url
     * response.sendRedirect(request.getContextPath()+"/user/tologin");
     * <p>
     * 2.或者返回json信息 returns(response, "token认证失败");
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET,DELETE,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, Access-Toke");

        String auth = request.getHeader(HttpHeaders.AUTHORIZATION);//AUTHORIZATION   Bearer token....
        String token = null;
        if (auth != null && auth.length() > 7) {
            token = auth.substring(7, auth.length());
        }
        System.out.println(token+"------------------");
        try {
            //token检验
            Map map = new JwtUtils().validateToken(token);

            //判断token是否登录，过期，单点登录等，使用redis存储token
            //在登录验证通过后将token更新到redis中,
//            String id= String.valueOf(map.get("id"));
//            String tokenCache=TokenCache.get(id);
//            if(!token.equals(tokenCache)){
//                returns(response, "认证失败，请重新登录");
//                return false;
//            }


            //权限管理
            if (check(handler, map)) {
                returns(response, "权限不足");
                return false;
            }
        } catch (Exception e) {
            logger.info(e.getLocalizedMessage());
            returns(response, "token认证失败");
            return false;
        }
        return true;
    }

    /**
     * 检查handler方法上的的注解与token中值是否匹配
     */
    public boolean check(Object handler, Map map) {
        int i = (int) map.get("role");
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Roles roles = method.getAnnotation(Roles.class);
        if (roles != null) {
            int t = roles.type();
            if (i != t) {
                return true;
            }
        }
        return false;
    }

    /**
     * 直接返回json信息
     */
    public void returns(HttpServletResponse response, String mess) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        ResponseResult r=ResponseResult.unauthorized(mess);
        String json = JSON.toJSONString(r);
        response.getWriter().write(json);
    }

}
